package com.lzh.hosp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzh.hosp.model.Doctor;
import com.lzh.hosp.model.OrderInfo;
import com.lzh.hosp.model.Patient;
import com.lzh.hosp.model.Schedule;
import com.lzh.hosp.model.vo.OrderInfoQueryVo;
import com.lzh.hosp.service.*;
import com.lzh.hosp.mapper.OrderInfoMapper;
import com.lzh.hosp.utils.CommonUtils;
import com.lzh.hosp.utils.RedisCache;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
* @author 59399
* @description 针对表【order_info(订单表)】的数据库操作Service实现
* @createDate 2023-03-26 11:15:23
*/
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo>
    implements OrderInfoService{

    @Autowired
    private ScheduleService scheduleService;

    @Autowired
    private DoctorService doctorService;

    @Autowired
    private DictService dictService;

    @Autowired
    private PatientService patientService;

    @Autowired
    private RedisCache redisCache;


    @Override
    public String add(OrderInfo orderInfo) {
        //判断排班是否还有余量
        Schedule schedule = scheduleService.getById(orderInfo.getScheduleId());
        if (schedule.getAvailableNumber()<0){//说明余量不足
            return null;
        }

        //判断是否重复挂号
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("card_no",orderInfo.getCardNo());
        wrapper.eq("schedule_id",orderInfo.getScheduleId());
        wrapper.and(queryWrapper->{
            queryWrapper.eq("order_status",0).or().eq("order_status",2).or().eq("order_status",4);//未支付或者已支付的不能重复挂号
        });
        OrderInfo info = baseMapper.selectOne(wrapper);
        if (!StringUtils.isEmpty(info)){//说明已重复挂号
            return null;
        }

        //向orderInfo设置其他值
        orderInfo.setOrderStatus(0); //0代表订单未支付
        orderInfo.setAmount(schedule.getAmount());

        //添加数据
        int insert = baseMapper.insert(orderInfo);

        //排班余量减1
        schedule.setAvailableNumber(schedule.getAvailableNumber()-1);
        scheduleService.updateById(schedule);

        //往redis存入订单号
        String orderInfoId = orderInfo.getId();
        redisCache.setCacheObject(orderInfoId,"1",5, TimeUnit.MINUTES);
        //备份键位
        redisCache.setCacheObject(orderInfoId+"orderInfo","1");

        return orderInfoId;
    }

    @Override
    public OrderInfo findById(String id) {
        OrderInfo orderInfo = baseMapper.selectById(id);

        //设置其他值
        Schedule schedule = scheduleService.getById(orderInfo.getScheduleId());
        //科室名
        String depname = dictService.getDictName(schedule.getDepcode());
        //医生相关信息
        Doctor doctor = doctorService.getById(schedule.getDocId());
        //设置值
        Map<String, Object> params = new HashMap<>();
        //候诊时间
        String workDate = new DateTime(schedule.getWorkDate()).toString("MM月dd日");
        String workTime = workDate+" "+CommonUtils.workTime(schedule.getWorkTime());
        //病人姓名
        String patientName = patientService.getPatientName(orderInfo.getCardNo());

        params.put("patientName",patientName);
        params.put("workTime",workTime);
        params.put("depname",depname);
        params.put("docname",doctor.getUsername());
        params.put("professionalTitle",doctor.getProfessionalTitle());
        params.put("timeout",redisCache.getTTL(id));
        orderInfo.setParams(params);
        return orderInfo;
    }

    @Override
    public List<OrderInfo> getByObj(OrderInfoQueryVo orderInfoQueryVo){
        QueryWrapper<OrderInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("card_no",orderInfoQueryVo.getCardNo());
        wrapper.orderByDesc("create_time");
        if (!StringUtils.isEmpty(orderInfoQueryVo.getDateRange())){
            Date[] date = orderInfoQueryVo.getDateRange();
            wrapper.ge("create_time",date[0]).le("create_time",date[1]);
        }
        List<OrderInfo> list = baseMapper.selectList(wrapper);
        for (OrderInfo orderInfo : list) {
            //设置其他值
            Schedule schedule = scheduleService.getById(orderInfo.getScheduleId());
            //科室名
            String depname = dictService.getDictName(schedule.getDepcode());
            //医生相关信息
            Doctor doctor = doctorService.getById(schedule.getDocId());
            //候诊时间
            String workDate = new DateTime(schedule.getWorkDate()).toString("MM月dd日");
            String workTime = workDate+" "+CommonUtils.workTime(schedule.getWorkTime());
            //设置值
            Map<String, Object> params = new HashMap<>();
            params.put("depname",depname);
            params.put("docname",doctor.getUsername());
            params.put("professionalTitle",doctor.getProfessionalTitle());
            params.put("workTime",workTime);
            orderInfo.setParams(params);
        }
        return list;
    }

    @Override
    public boolean patientRegistration(String orderInfoId) {
        //找出对应的医生id
        OrderInfo orderInfo = baseMapper.selectById(orderInfoId);
        Long scheduleId = orderInfo.getScheduleId();
        Schedule schedule = scheduleService.getById(scheduleId);
        Doctor doctor = doctorService.getById(schedule.getDocId());

        //找出对应的病人
        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        wrapper.eq("card_no",orderInfo.getCardNo());
        Patient patient = patientService.getOne(wrapper);
        //设置其他值
        Map<String,Object> params = new HashMap<>();
        params.put("overtime",0);//0表示未超时，1表示超时
        params.put("orderInfoId",orderInfoId);
        patient.setParams(params);

        //在redis中查询有无存在key为医生id的队列
        List<Patient> list = (List<Patient> )redisCache.getCacheObject("doctor:"+doctor.getId());
        if (!StringUtils.isEmpty(list)){//如果队列不为空
            //list转queue
            Queue<Patient> queue = new LinkedList<>(list);
            queue.offer(patient);
            redisCache.setCacheObject("doctor:"+doctor.getId(),queue);
            return true;
        }
        //如果队列为空
        Queue<Patient> patientQueue = new LinkedList<>();
        patientQueue.offer(patient);
        redisCache.setCacheObject("doctor:"+doctor.getId(),patientQueue);

        return true;
    }


}




